package org.example.maven.museumuser.common;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Component
public class RedisCommon {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    private static final ObjectMapper objectMapper=new ObjectMapper(); // Spring Boot 自动配置的 Jackson 序列化器




    //存入有效时间的键值对
    public  <T> void setTemporaryCode(String key,T value,Integer timeout, TimeUnit timeUnit) throws JsonProcessingException {
        // 1. 根据类型处理数据
        if (value instanceof String) {
            // String 类型直接存储
            stringRedisTemplate.opsForValue().set(key, (String) value, timeout, timeUnit);
        } else {
            try {
                // 对象类型转为 JSON 存储
                String json = objectMapper.writeValueAsString(value);
                stringRedisTemplate.opsForValue().set(key, json, timeout, timeUnit);
            } catch (JsonProcessingException e) {
                throw new RuntimeException("Failed to serialize value to JSON", e);
            }
        }
    }
    //存入没有时间限制的键值对
    public  <T> void setPermanentCode(String key,T value) throws JsonProcessingException {
        if (value instanceof String) {
            stringRedisTemplate.opsForValue().set(key, (String) value);
        }
        else {
            try {
                String json = objectMapper.writeValueAsString(value);
                stringRedisTemplate.opsForValue().set(key, json);
            } catch (JsonProcessingException e) {
                throw new RuntimeException("Failed to serialize value to JSON", e);
            }
        }
    }
    //将object对象反序列并返回
    public  <T> T getValueByObject(String key,Class<T> type) throws JsonProcessingException {
        return objectMapper.readValue(stringRedisTemplate.opsForValue().get(key),type);
    }

    //获取String类型的值
    public String getValueOfString(String key){
        return stringRedisTemplate.opsForValue().get(key);
    }

    //判断是否存在某个key
    public boolean checkHaveCode(String key){
        return stringRedisTemplate.hasKey(key);
    }

    //删除某个key
    public void deleteKey(String key){
        stringRedisTemplate.delete(key);
    }

    //尝试获取一个锁
    public boolean tryGetLock(String key,String value,Integer timeout){
        return stringRedisTemplate.opsForValue().setIfAbsent(key,value,timeout,TimeUnit.SECONDS);
    }
    //释放锁
    public void releaseLock(String key){
        String value =stringRedisTemplate.opsForValue().get(key);
        if(value.equals(key)){
            stringRedisTemplate.delete(key);
        }
    }



}
